<template>
  <div class="orders-view">
    <h2>我的订单</h2>

    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="order_number" label="订单号" width="200" />
      <el-table-column label="电影海报" width="100">
         <template #default="scope">
          <img :src="scope.row.poster_image" style="width: 50px; height: 70px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column prop="movie_title" label="电影名称" />
      <el-table-column prop="showtime" label="场次" />
      <el-table-column prop="seat" label="座位" />
      <el-table-column prop="price" label="总价 (元)" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 'confirmed'"
            type="danger"
            size="small"
            @click="cancelOrder(scope.row.id)"
          >
            取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '../utils/request'

const orders = ref([])

// P5: 封装获取订单 (P5 调用 P3 的 API)
const fetchOrders = async () => {
  try {
    const res = await request.get('/orders') // (P5: 因为有拦截器, Token 会自动带上)
    if (res.data.success) {
      orders.value = res.data.data
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取订单失败')
  }
}

// P5: 取消订单 (P5 调用 P3 的 API)
const cancelOrder = async (orderId) => {
  try {
    const res = await request.put(`/order/${orderId}/cancel`)
    if (res.data.success) {
      ElMessage.success('订单已取消')
      await fetchOrders() // 刷新列表
    }
  } catch (error) {
     ElMessage.error(error.response?.data?.message || '取消失败')
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-view { max-width: 1200px; margin: 0 auto; }
</style>